package com.meis.widget.praise;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.StackLayout;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import org.jetbrains.annotations.Nullable;

import java.security.SecureRandom;

/**
 * Created by wenshi on 2018/7/11.
 * Description 贝塞尔点赞控件
 */
public class BezierPraiseView extends StackLayout {

    private final SecureRandom mRandom;
    private BezierPraiseAnimator mBezierPraiseAnimator;
    private EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (getWidth() <= 0 || getHeight() <= 0) return;
            mBezierPraiseAnimator.startAnimation(mRandom.nextInt(getWidth()), mRandom.nextInt(getHeight()));
            mHandler.sendEvent(1, 200);
        }
    };

    public BezierPraiseView(Context context) {
        this(context, null);
    }

    public BezierPraiseView(Context context, @Nullable AttrSet attrs) {
        this(context, attrs, "");
    }

    public BezierPraiseView(Context context, @Nullable AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mBezierPraiseAnimator = new BezierPraiseAnimator(this);
        mRandom = new SecureRandom();

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                mHandler.sendEvent(1);
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                stop();
            }
        });
    }

    public void stop() {
        mHandler.removeAllEvent();
        mHandler = null;
    }
}
